package com.jzo2o.health.listener;

import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.enums.OrderStatusEnum;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.properties.TradeProperties;
import com.jzo2o.health.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;

import java.util.List;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {
    @Autowired
    private TradeProperties tradeProperties;

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_TRADE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        log.info("接收到支付结果状态的消息 ({})-> {}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);
        List<TradeStatusMsg> list = JSON.parseArray(msg, TradeStatusMsg.class);
        if(CollUtils.isEmpty(list)){
            return;
        }
        list.stream().filter(x->x.getProductAppId().equals(tradeProperties.getProductAppId())&&x.getStatusCode().equals(TradingStateEnum.YJS.getCode()))
                .forEach(y->ordersService.paySuccess(y.getProductOrderNo(),y.getTransactionId(),y.getPaySuccessTime()));
        log.info("消费成功");
    }
    @Autowired
    private IOrdersService ordersService;

    /**
     * 未支付订单超时后自动取消
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = MqConstants.Queues.ORDERS_CANCEL_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.ORDERS, delayed = "true"),
            key = MqConstants.RoutingKeys.ORDERS_CANCEL_KEY
    ))
    public void listenMsgForCancel(String id) {
        if(ObjectUtils.isNull(id)){
            return;
        }
        Long ordersId = Long.valueOf(id);
        Orders orders = ordersService.getById(ordersId);
        if(ObjectUtils.isNull(orders)){
            return;
        }
        if(!ObjectUtils.equals(orders.getOrderStatus(),0)){
            return;
        }
        ordersService.cancelOrdersByNoPay(orders,"未支付系统自动取消",true);
    }
}
